import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes,allAsyncRoutes,anyRoute } from '@/router/routes'
import { reqLogin, reqLogOut, reqUserInfo } from '@/api/acl/login';
import router from '@/router';
import _ from 'lodash'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//计算用户动态追加异步路由
// 对外暴露全部异步路由组件
//用户登录成功，用户信息里面包含的异步路由信息（需要动态注册的信息）
const findUserAsyncRoutes = (allAsyncRoutes:any,routes:any) =>{
  return allAsyncRoutes.filter((item:any)=>{
    if(routes.indexOf(item.name) != -1 ){
      if(item.children&&item.children.length>0){
        item.children = findUserAsyncRoutes(item.children,routes);
      }
      return true;
    }
  })
}
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,//token
    name: '',//用户名
    avatar: '',//头像
    menuRoutes: [],//左侧菜单展示区
    buttonsList:[]
  }),

  actions: {
    //点击登录按钮，由仓库发送请求
    async login(username: string, password: string) {
      try {
        //发送登录请求，返回token值
        let result = await reqLogin({ username, password });
        //仓库储存token
        this.token = result.token;
        //持久化存储token
        setToken(result.token);
        return '登录成功'
      } catch (error) {
        return Promise.reject('登录失败')
      }
    },

    //获取用户信息
    async getInfo() {
      try {
        // 发送请求获取用户信息
        let result = await reqUserInfo();
        //获取用户名字
        this.name = result.name;
        //获取用户头像
        this.avatar = result.avatar;
        //仓库储存当前用户按钮的权限
        this.buttonsList = result.buttons;
        //先计算当前用户需要展示的异步路由，定义异步路由与服务器返回的数据routes对比
        //深拷贝//每一个用户对比的异步路由应该一样
        let userRegisterAsyncRoute = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes),result.routes)
        //调用方法。动态添加用户注册异步路由+任意路由
        this.setRoute([...userRegisterAsyncRoute,anyRoute]);
        //修改仓库中menuRoutes中的属性值
        this.menuRoutes = [...staticRoutes,...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error);
      }
    },
    //动态添加路由
    setRoute(registerRoute:any){
      //追加路由
      registerRoute.forEach((item:any)=>{
        router.addRoute(item);
      })
    },

    async reset() {
      try {
        await reqLogOut();
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        //重置路由
        this.resetRoute();
        return 'ok'
      } catch (error) {
        return Promise.reject(error);
      }
    },
    //重置路由方法
    resetRoute(){
      //当前用户退出登录，应该清空全部异步路由
      //获取当前用户全部路由信息
      let allRoutes = router.getRoutes();
      allRoutes.forEach((item:any)=>{
        //删除全部路由
        router.removeRoute(item.name);
      });
      //常量路由动态添加
      staticRoutes.forEach((item:any)=>{
        router.addRoute(item);
      })
    }
  },
});
